package org.xxpay.pay.channel.hmapay;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayNotify;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author: pangxiaoyu
 * @date: 2020年2月25日15:50:00
 */
@Service
public class HmapayPayNotifyService extends BasePayNotify {

    private static final MyLog _log = MyLog.getLog(HmapayPayNotifyService.class);
    private static final String logPrefix = "【处理"+ HmapayConfig.CHANNEL_NAME+"支付回调】";

    @Override
    public String getChannelName() {
        return HmapayConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject doNotify(Object notifyData) {
        _log.info("====== 开始处理{}支付回调通知 ======", getChannelName());
        HttpServletRequest request = (HttpServletRequest) notifyData;
        JSONObject retObj = buildRetObj();
        Map<String, String> payContext = new HashMap();

        String respString = HmapayConfig.RETURN_VALUE_ERROR;
        try {
            PayOrder payOrder = verifyPayParams(request, payContext);
            if( payOrder == null ) { //验证参数失败
                retObj.put(PayConstant.RESPONSE_RESULT, HmapayConfig.RETURN_VALUE_ERROR);
                return retObj;
            }
            //订单已经支付完成
            if(payOrder.getStatus() == PayConstant.PAY_STATUS_SUCCESS || payOrder.getStatus() == PayConstant.PAY_STATUS_COMPLETE){
                retObj.put(PayConstant.RESPONSE_RESULT, HmapayConfig.RETURN_VALUE_SUCCESS);
                return retObj;
            }
            //上游通知 状态
            String channelOrderNo = payContext.get("queryId"); //上游订单号

            int updatePayOrderRows = commonService.payOrderService.updateStatus4Success(payOrder.getPayOrderId(), channelOrderNo);
            if (updatePayOrderRows != 1) {
                _log.error("{}更新支付状态失败,将payOrderId={},更新payStatus={}失败", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
                retObj.put(PayConstant.RESPONSE_RESULT, "处理订单失败");
                return retObj;
            }
            _log.error("{}更新支付状态成功,将payOrderId={},更新payStatus={}成功", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
            payOrder.setStatus(PayConstant.PAY_STATUS_SUCCESS);

            // 业务系统后端通知
            baseNotify4MchPay.doNotify(payOrder, true);
            _log.info("====== 完成处理{}支付回调通知 ======", getChannelName());
            respString = HmapayConfig.RETURN_VALUE_SUCCESS;
        } catch (Exception e) {
            _log.error(e, logPrefix + "处理异常");
        }
        retObj.put(PayConstant.RESPONSE_RESULT, respString);
        return retObj;
    }

    /**
     * 验通知参数
     * @return
     */
    public PayOrder verifyPayParams(HttpServletRequest request, Map<String, String> payContext) {

        // 校验结果是否成功
        String resultCode = request.getParameter("resultCode");                      // 状态
        String resultMsg = request.getParameter("resultMsg");                      // 状态说明
        String orderNum = request.getParameter("orderNum");              // 平台订单号
        String out_trade_no = request.getParameter("out_trade_no");		            // 商户订单号
        String type = request.getParameter("type");		    // 支付类型
        String orderMoney = request.getParameter("orderMoney");                      // 订单金额
        String payMoney = request.getParameter("payMoney");                      // 实际支付金额
        String finishTime = request.getParameter("finishTime");                      // 完成时间
        String createTime = request.getParameter("createTime");                      // 创建时间
        String userId = request.getParameter("userId");                      // 用户id
        String sign = request.getParameter("sign"); 		                    // 签名

        TreeMap<String, Object> paramMap = new TreeMap<>();
        paramMap.put("resultCode", resultCode);
        paramMap.put("resultMsg", resultMsg);
        paramMap.put("orderNum", orderNum);
        paramMap.put("out_trade_no", out_trade_no);
        paramMap.put("type", type);
        paramMap.put("orderMoney", orderMoney);
        paramMap.put("payMoney", payMoney);
        paramMap.put("finishTime", finishTime);
        paramMap.put("createTime", createTime);
        paramMap.put("userId", userId);

        _log.info("[{}], params={}, sign={}", logPrefix, paramMap, sign);

        // 验证状态
        if (!"1001".equals(resultCode)) {
            _log.error("状态错误 ,payOrderId={}, trade_status={}", out_trade_no, resultCode);
            return null;
        }

        // 查询payOrder记录
        String payOrderId = out_trade_no;
        PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
        if (payOrder == null) {
            _log.error("Can't found payOrder form db. payOrderId={}, ", payOrderId);
            return null;
        }

        // 核对金额
        if (!payOrder.getAmount().toString().equals(AmountUtil.convertDollar2Cent(payMoney))) {
            _log.error("金额不一致. orderAmount={},total_fee={},payOrderId={}", payOrder.getAmount(), payMoney, payOrderId);
            return null;
        }

        HmapayConfig hmapayConfig = new HmapayConfig(getPayParam(payOrder));
        // 验证签名
        String signValue = HmaUtil.createSign(paramMap, hmapayConfig.getKey());
        if(!sign.equals(signValue)) {
            _log.error("验证签名失败. payOrderId={}, ", payOrderId);
            return null;
        }
        return payOrder;
    }

}
